//
//  OrderSearchResultViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/12.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "OrderSearchResultViewController.h"
#import "OrderDetailViewController.h"
#import "OrderTableViewController.h"
#import "OrderTableViewController.h"
#import "MeatCartViewController.h"
#import "RecentlyChatListViewController.h"

#import "OrderHeaderCell.h"
#import "OrderFooterCell.h"
#import "OrderBodyCell.h"
#import "OrderNomalCell.h"

#import "LogisticsViewController.h"
#import "MeatPayViewController.h"
#import "OrderCancelBox.h"

@interface OrderSearchResultViewController ()

@property (nonatomic, strong) MeatOrderSumbitParam *sumbitParam;
@property (nonatomic, strong) MeatOrderDataModel *model;
@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSArray *reasons;
@property (nonatomic, strong) NSArray *icons;
@property (nonatomic, strong) UIImageView *showIcon;

@end

@implementation OrderSearchResultViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    {
        self.baseNavView.navTitleLabel.text = @"搜索结果";
        
        self.baseNavView.rightNavBtn.hidden = NO;
        [self.baseNavView.rightNavBtn setImage:[UIImage imageNamed:@"meat_order_more"] forState:UIControlStateNormal];
        @weakify(self);
        self.baseNavView.rightBlock = ^{
            @strongify(self);
            
            if (self.showIcon.alpha == 0 ) {
                
                [UIView animateWithDuration:AnimationTime animations:^{
                    self.showIcon.alpha = 1;
                }];
                
            }else{
                [self hideShopIcon];
            }

        };
    }
    
    {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window addSubview:self.showIcon];
    }
}

- (void)setupLayout
{
    self.reloadBtn.mj_y -= 100;
    self.reloadLab.mj_y -= 100;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(TJ_NavBarHeight, 0, 0, 0));
    }];
}


- (void)initData{
    
    [self requestOrderData];
}


- (void)requestOrderData{
    
    MeatOrderParam *param = [[MeatOrderParam alloc] init];
    param.memberId = kMemberId;
    NSNumber *page = [NSNumber numberWithInteger:self.page];
    param.page = page;
    param.limit = @10;
    param.type = @0;
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderListByParams:param] subscribeNext:^(MeatOrderListModel * _Nullable model) {
        @strongify(self);
        
        if (self.isRefresh) {
            
            [self endRefresh];
            if (self.datas.count >0) {
                [self.datas removeAllObjects];
            }
        }
        
        [model.page.list enumerateObjectsUsingBlock:^(MeatOrderItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.datas addObject:obj];
        }];
        
        if ([model.page.currPage intValue] >= [model.page.totalPage intValue]) {
            [self endLoadMoreMoData];
        }else{
            [self endLoadMore];
        }
        
        if (self.datas.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
        }
        
    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
}

//上拉加载更多
- (void)loadMore
{
    [super loadMore];
    [self requestOrderData];
}


//取消订单
- (void)requestCancelOrderById:(NSNumber *)goodId reason:(NSString *)reason
{
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderCancelByGoodId:goodId reason:reason] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        
        [self showHudWithMsg:@"取消订单成功"];
        [self refresh];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        
        NSString *contentText = error.userInfo[NSLocalizedDescriptionKey];
        [self showHudWithMsg:contentText];
    }];
}

//删除订单
- (void)requestDeleteOrderById:(NSNumber *)goodId{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderDeleteByGoodId:goodId] subscribeNext:^(NSNull * _Nullable x) {
        
        @strongify(self);
        
        [self showHudWithMsg:@"删除订单成功"];
        [self refresh];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        
        NSString *contentText = error.userInfo[NSLocalizedDescriptionKey];
        [self showHudWithMsg:contentText];
    }];
}

//确认收货
- (void)requestAcceptOrderById:(NSNumber *)goodId{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getOrderConfirmOverByGoodId:goodId] subscribeNext:^(NSNull * _Nullable x) {
        
        @strongify(self);
        
        [self showHudWithMsg:@"确认收货成功"];
        [self refresh];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        
        NSString *contentText = error.userInfo[NSLocalizedDescriptionKey];
        [self showHudWithMsg:contentText];
    }];
}



#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    MeatOrderItemModel *item = self.datas[section];
    return item.details.count + 4;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) return 44;
    if (indexPath.row == 1) return 34;
    MeatOrderItemModel *item = self.datas[indexPath.section];
    if (indexPath.row == item.details.count + 2) return 40;
    if (indexPath.row == item.details.count + 3) return 46;
    return 70;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = KClearColor;
    return sectionView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section < self.datas.count) {
        
        MeatOrderItemModel *item = self.datas[indexPath.section];
        if (indexPath.row < item.details.count + 4) {
            
            if (indexPath.row == 0) {
                
                OrderHeaderCell *headerCell = [tableView dequeueReusableCellWithIdentifier:@"OrderHeaderCell"];
                headerCell.shopName = item.shopName;
                
                switch ([item.goStatus integerValue]) {
                    case 1:
                        headerCell.orderStateType = OrderStateTyp_NoPaying;
                        break;
                    case 2:
                        headerCell.orderStateType = OrderStateType_NoSending;
                        break;
                    case 3:
                        headerCell.orderStateType = OrderStateType_NoAccept;
                        break;
                    case 4:
                        headerCell.orderStateType = OrderStateType_Finish;
                        break;
                    case 5:
                        headerCell.orderStateType = OrderStateType_Cancel;
                        break;
                    default:
                        break;
                }
                
#pragma mark - 删除订单
                @weakify(self);
                headerCell.dealCleanOrderBlock = ^{
                    @strongify(self);
                    
                    [self showMyAlertWithTitle:@"确定删除此订单？" message:@"订单删除后不可撤回" confirmBtnTitle:@"确定" callBack:^{
                        [self requestDeleteOrderById:item.goodsOrderId];
                    }];
                };
                
                return headerCell;
                
            }else if (indexPath.row == 1 || indexPath.row == item.details.count + 2){
                
                OrderNomalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderNomalCell"];
                
                if (indexPath.row == 1 ) {
                    cell.textLab.text = [NSString stringWithFormat:@"%@ %@", item.varietiesName, item.pigNum];
                    cell.textLab.textAlignment = 0;
                }else{
                    
                    cell.textLab.textAlignment = 2;
                    
                    NSString *shopNum = [NSString stringWithFormat:@"共%ld件商品 合计：",item.details.count];
                    NSString *price = [NSString stringWithFormat:@"¥%@",item.totalMoney];
                    NSString *text = [NSString stringWithFormat:@"%@ %@", shopNum, price];
                    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:text];
                    [attributedStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x5E5E5E) range:NSMakeRange(0, text.length)];
                    [attributedStr addAttribute:NSFontAttributeName value:mFont(13) range:NSMakeRange(0, text.length)];
                    
                    [attributedStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x4D4D4D) range:NSMakeRange(shopNum.length, price.length)];
                    [attributedStr addAttribute:NSFontAttributeName value:mMediumFont(17) range:NSMakeRange(shopNum.length +2, price.length-1)];
                    cell.textLab.attributedText = attributedStr;
                    
                }
                
                return cell;
                
            } else if (indexPath.row == item.details.count + 3){
                
                OrderFooterCell *footerCell = [tableView dequeueReusableCellWithIdentifier:@"OrderFooterCell"];
                
                switch ([item.goStatus integerValue]) {
                    case 1:
                        footerCell.orderStateType = OrderStateTyp_NoPaying;
                        break;
                    case 2:
                        footerCell.orderStateType = OrderStateType_NoSending;
                        break;
                    case 3:
                        footerCell.orderStateType = OrderStateType_NoAccept;
                        break;
                    case 4:
                        footerCell.orderStateType = OrderStateType_Finish;
                        break;
                    case 5:
                        footerCell.orderStateType = OrderStateType_Cancel;
                        break;
                        
                        
                    default:
                        break;
                }
                
#pragma mark - 更多
                @weakify(self);
                footerCell.dealMoreOperationBlock = ^{
                    @strongify(self);
                    
//                    if (self.jumpBlock) {
//                        self.jumpBlock(4);
//                    }
                };
                
#pragma mark - 冷链物流
                footerCell.dealLogisticsOrderBlock = ^{
                    @strongify(self);
                    
                    LogisticsViewController *vc = [[LogisticsViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                };
                
#pragma mark - 去支付
                footerCell.dealPayOrderBlock  = ^{
                    @strongify(self);
                    
                    MeatPayViewController *vc = [[MeatPayViewController alloc] init];
                    vc.parma = self.sumbitParam;
                    [self.navigationController pushViewController:vc animated:YES];
                };
                
#pragma mark - 取消订单
                footerCell.dealCancelOrderBlock  = ^{
                    @strongify(self);
                    
                    OrderCancelBox *box = [[OrderCancelBox alloc] init];
                    box.datas = self.reasons;
                    box.selectBlock = ^(NSString * _Nonnull text) {
                        
                        [self requestCancelOrderById:item.goodsOrderId reason:text];
                    };
                    [box showView];
                };
                
#pragma mark - 朋友代付
                footerCell.dealFriendPayOrderBlock  = ^{
                    @strongify(self);
                    
                    [self showHudWithMsg:@"朋友代付"];
                };
                
#pragma mark - 继续逛逛
                footerCell.dealBrowseOrderBlock  = ^{
                    @strongify(self);
                    
                    [self showHudWithMsg:@"继续逛逛"];
                };
#pragma mark - 确认收货
                footerCell.dealOkAcceptBlock  = ^{
                    @strongify(self);
                    
                    [self showMyAlertWithTitle:@"" message:@"是否确认收到此订单商品？" confirmBtnTitle:@"确定" callBack:^{
                        [self requestAcceptOrderById:item.goodsOrderId];
                    }];
                };
#pragma mark - 晒单评价
                footerCell.dealEvaluationOrderBlock  = ^{
                    @strongify(self);
                    
                    [self showHudWithMsg:@"晒单评价"];
                };
                
#pragma mark - 追加评价
                footerCell.dealAgainEvaluationOrderBlock  = ^{
                    @strongify(self);
                    
                    [self showHudWithMsg:@"追加评价"];
                };
                
                
                
                return footerCell;
            }
            
            OrderBodyCell *bodyCell = [tableView dequeueReusableCellWithIdentifier:@"OrderBodyCell"];
            MeatOrderDetailsModel *detailItem = item.details[indexPath.row - 2];
            bodyCell.item = detailItem;
            return bodyCell;
        }
    }
    
    return [UITableViewCell new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MeatOrderItemModel *item = self.datas[indexPath.section];
    OrderDetailViewController *vc = [[OrderDetailViewController alloc] init];
    vc.item = item;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - setter methods
#pragma mark - getter methods

- (UIImageView *)showIcon{
    
    if (!_showIcon) {
        _showIcon = [UIImageView makeImageByImageName:@"meat_shop_box_bg" cornerRadius:0];
        _showIcon.backgroundColor = KClearColor;
        _showIcon.size = CGSizeMake(144, 154);
        _showIcon.mj_x = KScreenWidth - _showIcon.width - 15;
        _showIcon.mj_y = TJ_StatusBarHeight + 40;
        _showIcon.alpha = 0;
        _showIcon.userInteractionEnabled = YES;
        
        NSArray *icons = @[@"chat_middle", @"icon_home", @"meat_buy_cart"];
        NSArray *titles = @[@"消息", @"首页", @"购物车"];
        
        @weakify(self);
        [icons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            @strongify(self);
            UIImageView *icon = [UIImageView makeImageByImageName:obj cornerRadius:0];
            icon.userInteractionEnabled = YES;
            icon.size = CGSizeMake(22, 22);
            icon.mj_y = 18 + (28 + icon.height)*idx ;
            icon.mj_x = 14;
            [self.showIcon addSubview:icon];
            
            
            UILabel *label = [UILabel makeLabelWithText:titles[idx] textColor:UIColorFromRGB(0x4A4A4A) font:mFont(14) textAliment:0];
            label.size = CGSizeMake(144 - icon.right - 5, 22);
            label.mj_x = icon.right + 5;
            label.mj_y = icon.mj_y;
            [self.showIcon addSubview:label];
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0, 50*idx, 144, 50);
            btn.tag = 200+idx;
            [self.showIcon addSubview:btn];
            
            [btn addTarget:self action:@selector(jumpRelatedController:) forControlEvents:UIControlEventTouchUpInside];
            
            if (idx >0) {
                CAShapeLayer *line = [CAShapeLayer layer];
                line.fillColor = UIColorFromRGB(0xEAEAEA).CGColor;
                UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 50*idx, self.showIcon.width, 1)];
                line.path = path.CGPath;
                [self.showIcon.layer addSublayer:line];
            }
        }];
        
    }
    return _showIcon;
}


- (void)jumpRelatedController:(UIButton *)btn{
    
    switch (btn.tag) {
        case 200:
        {
            [self chat];
        }
            break;
            
        case 201:
        {
            
        }
            break;
            
        default:
        {
            MeatCartViewController *vc = [[MeatCartViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
    }
    
    self.showIcon.alpha = 0;
}

//我想聊聊
- (void)chat {
    
    //校验聊天是否登陆成功，否则重新登录
    if ([UserInfoDataProvider sharedInstance].userInfo.isIMLogin) {
        
        @weakify(self);
        [self pushToViewController:^{
            @strongify(self);
            [self.navigationController pushViewController:[[RecentlyChatListViewController alloc] init] animated:YES];
        }];
        
    } else {
        //如果没登录过
        NSString *userSig = [UserInfoDataProvider sharedInstance].userInfo.userSig;
        NSString *userName = [UserInfoDataProvider sharedInstance].userInfo.memberNum;
        [[ChatManager sharedInstance] loginIMWithUserName:userName userSig:userSig succ:^{
            [self toastWithContent:@"聊天登录成功"];
            UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
            userInfo.isIMLogin = YES;
            [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        } fail:^(int code, NSString * _Nonnull msg) {
            [self toastWithContent:msg];
        }];
        [self.navigationController pushViewController:[[RecentlyChatListViewController alloc] init] animated:YES];
    }
}


- (void)hideShopIcon{
    
    @weakify(self);
    [UIView animateWithDuration:AnimationTime animations:^{
        @strongify(self);
        self.showIcon.alpha = 0;
    }];
}


- (MeatOrderDataModel *)model{
    
    if (!_model) {
        _model = [[MeatOrderDataModel alloc] init];
    }
    return _model;
}

- (NSMutableArray *)datas{
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSArray *)reasons{
    
    if (!_reasons) {
        _reasons = @[@"我不想要了", @"信息填写有误，重新拍", @"下错单了，取消重新下单", @"等待时间太长", @"其它原因"];
    }
    return _reasons;
}

- (NSArray *)icons{
    
    if (!_icons) {
        _icons = @[@"meat_order_search", @"meat_order_more"];
    }
    return _icons;
}


- (MeatOrderSumbitParam *)sumbitParam{
    
    if (!_sumbitParam) {
        _sumbitParam = [[MeatOrderSumbitParam alloc] init];
        _sumbitParam.memberId = kMemberId;
        _sumbitParam.shopId = @1;
        _sumbitParam.remark = @"";
        _sumbitParam.goType = @"4";
        _sumbitParam.memberStatus = @1;
    }
    return _sumbitParam;
}

#pragma mark - override methods

- (void)registerTableViewCell
{
    self.tableView.separatorColor = KClearColor;
    
    [self.tableView registerClass:[OrderNomalCell class] forCellReuseIdentifier:@"OrderNomalCell"];
    [self.tableView registerClass:[OrderHeaderCell class] forCellReuseIdentifier:@"OrderHeaderCell"];
    [self.tableView registerClass:[OrderFooterCell class] forCellReuseIdentifier:@"OrderFooterCell"];
    [self.tableView registerClass:[OrderBodyCell class] forCellReuseIdentifier:@"OrderBodyCell"];
    
    
    UIView *footer = [UIView new];
    footer.backgroundColor = mBackgroudColor;
    footer.frame = CGRectMake(0, 0, KScreenWidth, 10);
    self.tableView.tableFooterView = footer;
    
}

@end
